// Global Variables.
var PAGENAMES = ['list', 'bar', 'profile'];

/**
 * Find the number of the page in function of its name.
 * @param {String} pageName Name of the page.
 * @return {Number} Number of the page. 
 */
function findPageNum(pageName) {
  for (var i = 0; i < PAGENAMES.length; i++) {
    if (PAGENAMES[i] == pageName) {
      return i;
    }  
  }
  return -1;
}

/**
 * Swipe to the page asked.
 * @param {String} pageName Name of the page.
 * @param {String} pathname Name of the new path.
 * @param {Number} Number of the page.
 */
function swipeToPage(pageName, numPage, pathname, push) {
  if (numPage == undefined) {
    numPage = findPageNum(pageName);
  }
  if (pathname == undefined) {
  	pathname = pageName;
  }
  mySwipe.slide(numPage);
  $('#header a').removeClass('selected'); 
  $('#header' + (numPage + 1)).addClass('selected');
  if (push) {
    history.pushState({path: pathname}, "State " + pathname, pathname);    
  }
};

/**
 * Go to page asked in function of a path
 * @param {String} pathname Path called
 * @param {boolean?} push Whether we want to push the path to url.
 * @return {boolean} Whether the route has been successful
 */
function routePage(pathname, push) {
  if (push == undefined) {
    push = true;
  }
  var pathsplit = pathname.split('/');
  if (pathsplit.length == 3) {
    if (pathsplit[1] == PAGENAMES[1]) {
      buildBarPage(pathsplit[2]);
    }
  }
  var numPage = findPageNum(pathsplit[1]);
  if (numPage > -1) {
    // _gaq.push(['_trackPageview', '/fake/' + pathname]);
    swipeToPage(pathsplit[1], numPage, pathname, push);
    return true;
  }
};

/**
 * Handles the pop state event.
 * @param event
 */
function handlerPopState(event) {
   routePage(event.currentTarget.location.pathname, false);
}

/**
 * Build the bar page in function of its demanded bar.
 * @param {String} barName Name of the bar
 */
function buildBarPage(barName) {
  $('#barPage').html('<div class="ui-loader ui-body-a ui-corner-all"'
      + 'style="top: 128.5px;display:block;"><span class="ui-icon ui-icon-loading spin"></span>'
	  + '<h1>loading</h1></div>');
  $.ajax({
	type: 'POST',
	url: '/getSimpleBarJson',
    data: {barName: barName},
    success: function(data) {
    	var jsonObj = $.parseJSON(data);
    	if (jsonObj['success']) {
    		$('#barPage').html(jsonObj['barPage']);
    		updateViews($.parseJSON(jsonObj['data']));
    		$('#bar-profile').trigger('create');
    	}
    }
  });
}

/**
 * Delete messages from view.
 */
function deleteMessages() {
  $('.errorMsg').remove();
}

function geolocaliseUser() {
   setTimeout(
	   function() {
	     if (navigator.geolocation) {
	       navigator.geolocation.getCurrentPosition(function(position) {
	          saveCoordinate(position.coords.latitude,
	              position.coords.longitude);
	      });
	     }
	   }, 0);	
}


//==============================================================================
// Listeners for the navigation.
//==============================================================================

/**
 * Listen for any attempts to call changePage().
 */
$(document).bind( "pagebeforechange", function( e, data ) {
  if ( typeof data.toPage === "string" ) {
    var u = $.mobile.path.parseUrl( data.toPage );
    e.preventDefault();
    if (routePage(u.pathname)) {
      e.preventDefault();
    }
  }
});

$(window).bind('popstate', handlerPopState);

$(document).ready(function() {
  var currentPage = $('#currentPage').html();
  var numPage = findPageNum(currentPage);
  window.mySwipe = new Swipe(document.getElementById('slider'),
      {startSlide: numPage, callback: callbackSwipe});
  selectHeader(numPage + 1);

  $('#listBar').height($(window).height());
  
});

function callbackSwipe() {
	selectHeader(mySwipe.getPos() + 1);
}

function selectHeader(numPage) {
  $('#footer a').removeClass('selected');
  $('#footer a').removeClass('ui-btn-active');
  
  $('#footer #header' + (numPage)).addClass('selected');
  $('#footer #header' + (numPage)).addClass('ui-btn-active');
}

